/*
 * Copyright 2018 The JA-SIG Collaborative. All rights reserved.
 * distributed with thi file and available online at
 */
package com.lap.scp.admin.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.lap.scp.erp.bean.ExcelType;

/**
 * <pre>
 * excel输入输出工具
 * </pre>
 * 
 * @author 劳水生 Exp
 * @Date 2018年10月20日 上午7:55:03
 * @since 1.0
 */
public abstract class ExcelUtils {
	/**
	 * logback日志对象。
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtils.class);

	/***
	 * 设置下载头信息
	 * 
	 * @param response
	 * @param fileName
	 */
	public static void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			fileName = URLEncoder.encode(fileName, Constants.UTF);
		} catch (UnsupportedEncodingException ex) {
			LOGGER.error(ex.getLocalizedMessage(), ex);
		}
		response.setContentType("application/octet-stream;charset=utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
		response.addHeader("Pargam", "no-cache");
		response.addHeader("Cache-Control", "no-cache");
	}

	/**
	 * 输出excel文件
	 * 
	 * @param wb
	 * @param response
	 */
	public static void writeExcel(Workbook wb, HttpServletResponse response) {
		try (OutputStream stream = response.getOutputStream()) {
			wb.write(stream);
		} catch (IOException e) {
			LOGGER.error(e.getLocalizedMessage(), e);
		}
	}

	/**
	 * 输出excel头信息
	 * 
	 * @param wb
	 * @param header
	 * @param sheetName
	 */
	public static void writeHeader(Workbook wb, String[] header, String sheetName) {
		if (header == null || header.length == 0) {
			return;
		}
		Sheet sheet = wb.createSheet(sheetName);
		Row row = sheet.createRow(0);

		Cell cell = row.createCell(0);
		cell.setCellValue(Constants.INDEX);

		for (int index = 0; index < header.length; index++) {
			cell = row.createCell(index + 1);
			cell.setCellValue(header[index]);
		}
	}

	/**
	 * 输出excel 内容信息
	 * 
	 * @param wb
	 * @param excelTeys
	 * @param list
	 * @param sheetName
	 * @param startRow
	 */
	@SuppressWarnings("unchecked")
	public static void writeContent(Workbook wb, ExcelType[] excelTeys, List<?> list, String sheetName, int startRow) {
		if (list == null || list.isEmpty()) {
			return;
		}
		Sheet sheet = wb.getSheet(sheetName);
		Row row;
		Cell cell;
		for (int i = 0; i < list.size(); i++) {
			row = sheet.createRow(startRow + i + 1);
			cell = row.createCell(0);
			cell.setCellValue(startRow + i + 1);

			String json = JSON.toJSONString(list.get(i));
			Map<String, Object> map = JSON.parseObject(json, Map.class);

			for (int j = 0; j < excelTeys.length; j++) {
				cell = row.createCell(j + 1);
				ExcelType type = excelTeys[j];
				Object obj = map.get(type.getKey());

				if (obj != null) {
					if (type.getClassType().equals("double")) {
						BigDecimal temp = (BigDecimal) obj;
						cell.setCellValue(temp.doubleValue());
					} else if (type.getClassType().equals("int")) {
						int temp = (int) obj;
						cell.setCellValue(temp);
					} else if (type.getClassType().equals("date")) {
						cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format(obj));
					} else {
						cell.setCellValue(Objects.toString(obj));
					}
				} else {
					cell.setCellValue("-");
				}
			}
		}
	}

}
